import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'
import { Base64 } from 'js-base64'

// 访问等级
enum ViewLevel {
    Def,
    Nil
}

// jwt 载荷
type CtpJwtPayload = {
  id:number|null
  nickname:string|null
  email:string|null
  iss:string|null
  sub:string|null
  aud:string[]|null
  exp:number|null
  nbf:number|null
  iat:number|null
  jti:string|null
}

// 路由注册
const routes: Array<RouteRecordRaw> = [
  // 默认路由
  {
    path: "/",
    meta: {
      level: ViewLevel.Nil
    },
    redirect: "/MainPage/Market"
  },
  // 壳页面
  {
    path: "/MainPage",
    name: "MainPage",
    meta: {
      level: ViewLevel.Nil
    },
    component: () => import("../views/MainPage.vue"),
    children: [
      {
        path: "Market",
        name: "Market",
        meta: {
          level: ViewLevel.Nil
        },
        component: () => import("../views/Market.vue")
      },
      {
        path: "GoodDetail/:goodId",
        name: "GoodDetail",
        meta: {
          level: ViewLevel.Nil
        },
        component: () => import("../views/GoodDetail.vue")
      },
      {
        path: "ListBuy",
        name: "ListBuy",
        meta: {
          level: ViewLevel.Def
        },
        component: () => import("../views/ListBuy.vue")
      },
      {
        path: "ListSale",
        name: "ListSale",
        meta: {
          level: ViewLevel.Def
        },
        component: () => import("../views/ListSale.vue")
      },
      {
        path: "ListDeal",
        name: "ListDeal",
        meta: {
          level: ViewLevel.Def
        },
        component: () => import("../views/ListDeal.vue")
      },
      {
        path: "UserInfo",
        name: "UserInfo",
        meta: {
          level: ViewLevel.Def
        },
        component: () => import("../views/UserInfo.vue")
      },
      {
        path: "UserAccount",
        name: "UserAccount",
        meta: {
          level: ViewLevel.Def
        },
        component: () => import("../views/UserAccount.vue")
      },
    ]
  },
  // 登录页面
  {
    path: "/LoginPage",
    name: "LoginPage",
    meta: {
      level: ViewLevel.Nil
    },
    component: () => import("../views/LoginPage.vue")
  },
  // 404路由
  {
    path: "/:pathMatch(.*)",
    name: "NotFound",
    meta: {
      
      level: ViewLevel.Nil
    },
    component: () => import("../views/404Error.vue")
  }
]

// 路由对象
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


// 全局路由守卫（比较路由等级）
router.beforeEach((to, from, next) => {
  // 旧等级判断
  let power:number|null = store.getters.power
  if (power == null) {
    let oldJwt = localStorage.getItem("jwt")
    if (oldJwt == null) {
      power = 1
      store.commit("LOG_NEW_POWER", 1)
    } else {
      let json = Base64.decode(oldJwt.split(".")[1])
      let claims = JSON.parse(json)
      let exp = (claims as CtpJwtPayload).exp
      localStorage.setItem("claims", JSON.stringify(claims))
      if (exp != null && exp*1000 > new Date().valueOf()) {
        store.dispatch("changeLoginStatus", {
          claims: claims,
          jwt: oldJwt
        })
        power = 0
      } else {
        localStorage.clear()
        power = 1
      }
    }
  }
  // 类型保护
  if (typeof to.meta.level === 'number') {
    if(power != null && to.meta.level >= power) {
      next()
    } else if (to.meta.level == ViewLevel.Nil || to.meta.level == undefined) {
      next()
    } else {
      next({name: "LoginPage"}) // 级别不够，退回主页面
    }
    return
  }
  next({name: "LoginPage"})
  return
})

export default router